package com.example.dbmeta.meta.common;

import org.springframework.data.domain.AuditorAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

public class MyAuditorAware implements AuditorAware<String> {
    //需要实现AuditorAware接口，返回当前的用户ID
//    @Override
//    public Optional<Integer> getCurrentAuditor() {
//        ServletRequestAttributes servletRequestAttributes =
//                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        Integer userId = (Integer) servletRequestAttributes.getRequest().getSession().getAttribute("userId");
//        return Optional.ofNullable(userId);
//    }
    @Override
    public Optional<String> getCurrentAuditor() {
        // 尝试从 session 获取用户
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        String username = null;

        if (attributes != null) {
            // 从 session 获取用户
            username = (String) attributes.getRequest()
                    .getSession()
                    .getAttribute("username");
        }

        // 如果没有获取到用户，返回默认的 "admin"
        return Optional.ofNullable(username).or(() -> Optional.of("admin"));
    }
}